<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <div class="FormBoPermissionEdit">
                    <div>
                        <a-form-model ref="form"  :model="mdl" :rules="rules" >
                            <a-form-model-item  :label="formBoListI18n('permissionName','权限名称')" prop = "name">
                                <div class="FormBoPermissionEdit-head">
                                    <div style="flex:1">
                                        <a-input :placeholder="formBoListI18n('PleasePermissionname','请输入权限名称')" v-model="mdl.name"/>
                                    </div>
                                    <div style="margin-left: 10px"><a-checkbox v-model="permissionStatus">{{formBoListI18n('enabledOrNot','启用')}}</a-checkbox></div>
                                </div>
                            </a-form-model-item>
                        </a-form-model>
                    </div>
                    <!--         内容          -->
                    <div class="FormBoPermissionEdit-common">
                        <div class="FormBoPermissionEdit-common-le">
                            <div class="FormBoPermissionEdit-le_hear">
                                {{formBoListI18n('Organization','组织或以下/用户/用户组配置')}}
                                <a-tooltip>
                                    <template slot="title">
                                        {{formBoListI18n('usersRight','配置哪些组织或以下/用户/用户组，拥有右边配置的列表资源')}}
                                    </template>
                                    <a-icon type="question-circle-o"/>
                                </a-tooltip>
                            </div>
                            <div class="FormBoPermissionEdit-le_common">
                                <div>
                                    <a-radio style="width: 80px" @change="onChangeAll" v-model="allType">{{formBoListI18n('all','所有人')}}</a-radio>
                                    <a-radio style="width: 80px" @change="onChangeShowList" v-model="showList">{{formBoListI18n('custom','自定义')}}
                                    </a-radio>
                                </div>
                                <template v-if="showList">
                                    <a-alert style="margin: 15px 0px 5px 0px" :message="formBoListI18n('authDescription','如果勾选了不包含，是除开选中的都有权限，不勾选则选中的有权限')"
                                             type="info" show-icon/>
                                    <ul>
                                        <li v-for="(dataObj, index) in typeList">
                                            <form-user-or-group :show="false" @change="aliskt" ref="preview"
                                                                :dataObj="dataObj"></form-user-or-group>
                                        </li>
                                    </ul>
                                </template>
                            </div>
                        </div>
                        <div class="FormBoPermissionEdit-common-ri">
                            <div class="FormBoPermissionEdit-le_hear">
                                {{formBoListI18n('ListResource','列表资源')}}
                                <a-tooltip>
                                    <template slot="title">
                                        {{formBoListI18n('ListResources','列表资源包含以下：字段权限（电脑端+移动端）功能按钮权限（电脑端+移动端）数据权限')}}
                                    </template>
                                    <a-icon type="question-circle-o"/>
                                </a-tooltip>
                            </div>
                            <!--列表资源-->
                            <div class="FormBoPermissionEdit-common-list">
                                <!--数据权限-->
                                <div class="FormBoPermissionEdit-common-list-name">
                                    <div style="flex: 1">{{formBoListI18n('DataPermissions','数据权限')}}</div>
                                    <a-checkbox v-model="datasStatus">{{formBoListI18n('enabledOrNot','启用')}}</a-checkbox>
                                </div>
                                <div class="FormBoPermissionEdit-jurisdiction">
                                    <div style="margin-bottom: 10px">
                                        <a-checkbox :indeterminate="indeterminate['datas']" :checked="checkAll['datas']" @change="onCheckAllChange($event,'datas')">{{formBoListI18n('selectAll','全选')}}</a-checkbox>
                                    </div>
                                    <a-checkbox-group class="jurisdiction-common-checkbox" v-model="checkedList['datas']" :options="checkedBoxSource['datas']"
                                                      @change="onChange($event,'datas')"/>
                                </div>
                                <div class="FormBoPermissionEdit-authority-list">
                                    <div class="FormBoPermissionEdit-name-list" style="border-right: solid 1px #eeeeee;">
                                        <div class="FormBoPermissionEdit-common-list-name">
                                           <div style="flex: 1">{{formBoListI18n('fieldPermiss','字段权限')}}</div>
                                            <a-checkbox v-model="fieldsStatus">{{formBoListI18n('enabledOrNot','启用')}}</a-checkbox>
                                        </div>
                                        <div class="authority-list-common">
                                            <div class="authority-common">
                                                <div class="FormBoListEditPermissionConf-list-head">{{formBoListI18n('PCPpermission','PC端权限')}}</div>
                                                <div class="FormBoListEditPermissionConf-list-name">
                                                    <div>
                                                        <a-checkbox :indeterminate="indeterminate['fields']" :checked="checkAll['fields']" @change="onCheckAllChange($event,'fields')">{{formBoListI18n('selectAll','全选')}}</a-checkbox>
                                                    </div>
                                                    <a-tree
                                                        style="margin-left: -25px;"
                                                        checkable
                                                        v-model="checkedList['fields']"
                                                        @check="onChange($event,'fields')"
                                                        :treeData="checkedBoxTree['fields']"
                                                    ></a-tree>
                                                </div>
                                            </div>
                                            <div class="authority-common" style="border-right: none">
                                                <div class="FormBoListEditPermissionConf-list-head">{{formBoListI18n('mobilePermission','mobile权限')}}</div>
                                                <div class="FormBoListEditPermissionConf-list-name">
                                                    <div style="margin-bottom: 10px">
                                                        <a-checkbox :indeterminate="indeterminate['mobileFields']" :checked="checkAll['mobileFields']" @change="onCheckAllChange($event,'mobileFields')">{{formBoListI18n('selectAll','全选')}}</a-checkbox>
                                                    </div>
                                                    <a-checkbox-group class="jurisdiction-common-checkbox" v-model="checkedList['mobileFields']" :options="checkedBoxSource['mobileFields']"
                                                                      @change="onChange($event,'mobileFields')"/>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="FormBoPermissionEdit-name-list">
                                        <div class="FormBoPermissionEdit-common-list-name">
                                            <div style="flex: 1">{{formBoListI18n('buttonPermissions','功能按钮权限')}}</div>
                                            <a-checkbox v-model="buttonsStatus">{{formBoListI18n('enabledOrNot','启用')}}</a-checkbox>
                                        </div>
                                        <div class="authority-list-common">
                                            <div class="authority-common">
                                                <div class="FormBoListEditPermissionConf-list-head">{{formBoListI18n('PCPpermission','PC端权限')}}</div>
                                                <div class="FormBoListEditPermissionConf-list-name">
                                                    <a-checkbox :indeterminate="indeterminate['buttons']" :checked="checkAll['buttons']" @change="onCheckAllChange($event,'buttons')">{{formBoListI18n('selectAll','全选')}}</a-checkbox>
                                                    <a-tree
                                                        style="margin-left: -25px;"
                                                        checkable
                                                        v-model="checkedList['buttons']"
                                                        @check="onChange($event,'buttons')"
                                                        :treeData="checkedBoxTree['buttons']"
                                                    ></a-tree>
                                                </div>
                                            </div>
                                            <div class="authority-common" style="border-right: none">
                                                <div class="FormBoListEditPermissionConf-list-head">{{formBoListI18n('mobilePermission','mobile权限')}}</div>
                                                <div class="FormBoListEditPermissionConf-list-name">
                                                    <a-checkbox style="margin-bottom: 10px" :indeterminate="indeterminate['mobileButtons']" :checked="checkAll['mobileButtons']" @change="onCheckAllChange($event,'mobileButtons')">{{formBoListI18n('selectAll','全选')}}</a-checkbox>
                                                    <a-checkbox-group class="jurisdiction-common-checkbox" v-model="checkedList['mobileButtons']" :options="checkedBoxSource['mobileButtons']"
                                                                      @change="onChange($event,'mobileButtons')"/>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
import FormBoPermissionApi from '@/api/form/core/formBoPermission'
import {RxDialog, BaseFormModel} from "@lowcode/jpaas-common-lib";
import FormUserOrGroup from "@/views/modules/form/core/formPermission/FormUserOrGroup";
import FormPermissionApi from "@/api/form/core/formPermission";


export default {
    name: 'FormBoPermissionEdit',
    props: ["boListObj", "columns", "buttons", "dataConf", "mobileCols", "mobileButton"],
    mixins: [BaseFormModel],
    components: {
        RxDialog,
        FormUserOrGroup
    },
    data() {
        return {
            i18nCurrent:"",
            rules: {
                name: [{required: true, message: this.formBoListI18n('PleasePermissionname','请输入权限名称'), trigger: 'change'}]
            },
            permissionStatus: false,
            fieldsStatus: false,
            buttonsStatus: false,
            datasStatus: false,
            showList: false,
            typeList: [],
            allType: false,
            settingObj: {
                setting: "everyone",
                settingName: this.formBoListI18n('all','所有人')
            },
            activeKey: "fields",
            indeterminate: {
                fields: false,
                mobileFields: false,
                buttons: false,
                mobileButtons: false,
                datas: false
            },
            checkAll: {
                fields: false,
                mobileFields: false,
                buttons: false,
                mobileButtons: false,
                datas: false
            },
            checkedList: {
                fields: [],
                mobileFields: [],
                buttons: [],
                mobileButtons: [],
                datas: []
            },
            checkedBoxMap:{
                fields:{}
            },
            checkedBoxTree:{
                fields:[],
                buttons:[]
            },
            checkedBoxSource: {
                fields: [],
                mobileFields: [],
                buttons: [],
                mobileButtons: [],
                datas: []
            }
        }
    },
    methods: {
        formBoListI18n(name,text,key){
            return this.$ti18(name,text,"FormBoPmt.FormBoListEditPermissionConf",key);
        },
        onload_(values) {
            this.init();
            var self = this;
            FormPermissionApi.getPermissionList().then((res) => {
                self.setTypeValue(res.data, values ? values.rightJson : null);
            })
            this.permissionStatus = values?values.status == "YES":true;
            this.fieldsStatus = values?values.fieldsStatus == "YES":true;
            this.buttonsStatus = values?values.buttonsStatus == "YES":true;
            this.datasStatus = values?values.datasStatus == "YES":true;
            if (values) {
                this.checkedList['fields'] = values.fields ? values.fields.split(",") : [];
                this.checkedList['buttons'] = values.buttons ? values.buttons.split(",") : [];
                this.checkedList['datas'] = values.datas ? values.datas.split(",") : [];
                this.checkedList['mobileFields'] = values.mobileFields ? values.mobileFields.split(",") : [];
                this.checkedList['mobileButtons'] = values.mobileButtons ? values.mobileButtons.split(",") : [];
                this.onChange(this.checkedList['fields'], 'fields');
                this.onChange(this.checkedList['buttons'], 'buttons');
                this.onChange(this.checkedList['datas'], 'datas');
                this.onChange(this.checkedList['mobileFields'], 'mobileFields');
                this.onChange(this.checkedList['mobileButtons'], 'mobileButtons');
            }
        },
        setTypeValue(data, value) {
            this.typeList = data
            if (!value || 'everyone' == value) {
                this.allType = true
            } else if ('custom' == value) {
                this.showList = true
            } else {
                var selectObj = JSON.parse(value)
                for (var i = 0; i < this.typeList.length; i++) {
                    var typeObj = this.typeList[i]
                    var isContinue = false
                    for (var key in selectObj) {
                        if (key == typeObj.type) {
                            typeObj.values = selectObj[key].values
                            typeObj.names = selectObj[key].names
                            typeObj.include = selectObj[key].include
                            isContinue = true
                            break
                        }
                    }
                    if (isContinue) {
                        continue
                    }
                }
                this.showList = true
            }
        },
        parseTree(arr,keyField,titleField){
          if(!arr){
            return null;
          }
          return arr.map(item => {
            return {title: item[titleField], key: item[keyField], children:this.parseTree(item.children,keyField,titleField)};
          })
        },
        parseList(arr,type,valueField,labelField){
          arr.forEach(item=>{
            this.checkedBoxSource[type].push({value:item[valueField],label:item[labelField]});
            if(item.children){
              this.parseList(item.children,type,valueField,labelField);
            }
          })
        },
        init() {
            this.parseList(this.columns,"fields","field","header");
            this.checkedBoxSource['fields'].forEach(item=>{
              this.checkedBoxMap[item.field]=item;
            });
            this.checkedBoxTree['fields'] = this.parseTree(this.columns,"field","header");
            this.parseList(this.buttons,"buttons","btnName","btnLabel");
            this.checkedBoxTree['buttons'] = this.parseTree(this.buttons,"btnName","btnLabel");
            this.checkedBoxSource['datas'] = this.dataConf.map(item => {
                return {label: item.name, value: item.id};
            })
            this.checkedBoxSource['mobileFields'] = this.mobileCols.map(item => {
                return {label: item.header, value: item.field};
            })
            this.checkedBoxSource['mobileButtons'] = this.mobileButton.map(item => {
                return {label: item.btnLabel, value: item.btnName};
            })
        },
        get(id) {
            return FormBoPermissionApi.get(id);
        },
        getCurrentI18n(){
          this.i18nCurrent= window.localStorage.getItem("language");
          if(!this.i18nCurrent){
            this.i18nCurrent=this.i18nDefault;
          }
        },
        parseI18n(obj) {
          let i18nJson = JSON.parse(obj.i18nJson);
          let val=i18nJson[this.i18nCurrent];
          return val?val:obj.header;
        },
        validForm(values) {
            if(this.fieldsStatus) {
              if (this.checkedList['fields'].length == 0) {
                this.$message.warning(this.formBoListI18n('permissionsMust', '字段权限必须选择一个！'));
                return false;
              }
              if(this.boListObj.dataStyle=='tree' && !this.checkedList['fields'].includes(this.boListObj.textField)){
                if(!this.boListObj.textField){
                  this.$message.warning(this.formBoListI18n('textFieldMust','请先配置树节点字段！'));
                }else{
                  this.$message.warning(this.formBoListI18n('textFieldMustStart', '树节点字段[')+this.parseI18n(this.checkedBoxMap[this.boListObj.textField])+this.formBoListI18n('textFieldMustEnd', ']必须选择！'));
                }
                return false;
              }
              if (this.checkedList['mobileFields'].length == 0) {
                this.$message.warning(this.formBoListI18n('mobilePermissionsMust', '手机端字段权限必须选择一个！'));
                return false;
              }
            }
            return true;
        },
        save() {
            this.mdl.boListId = this.boListObj.id;
            this.mdl.appId = this.boListObj.appId;
            this.mdl.status = this.permissionStatus ? 'YES' : 'NO';
            this.mdl.fieldsStatus = this.fieldsStatus ? 'YES' : 'NO';
            this.mdl.buttonsStatus = this.buttonsStatus ? 'YES' : 'NO';
            this.mdl.datasStatus = this.datasStatus ? 'YES' : 'NO';
            this.mdl.fields = this.checkedList['fields'].join(",");
            this.mdl.buttons = this.checkedList['buttons'].join(",");
            this.mdl.datas = this.checkedList['datas'].join(",");
            this.mdl.mobileFields = this.checkedList['mobileFields'].join(",");
            this.mdl.mobileButtons = this.checkedList['mobileButtons'].join(",");
            this.mdl.rightJson = this.settingObj.setting;
            this.mdl.rightJsonName = this.settingObj.settingName;
            return FormBoPermissionApi.save(this.mdl);
        },
        onChange(checkedList, type) {
            //勾选时，做一个全选的按钮状态更新
            this.indeterminate[type] = !!checkedList.length && checkedList.length < this.checkedBoxSource[type].length;
            this.checkAll[type] = checkedList.length === this.checkedBoxSource[type].length;
        },
        onCheckAllChange(e, type) {
            //全选操作
            this.checkedList[type] = e.target.checked ? this.checkedBoxSource[type].map(item => {
                return item.value;
            }) : [];
            this.indeterminate[type] = false;
            this.checkAll[type] = e.target.checked;
        },
        onChangeAll(e) {
            if (this.allType) {
                this.showList = false;
            }
            this.changeType()
        },
        onChangeShowList(e) {
            if (this.showList) {
                this.allType = false;
            }
            this.changeType();
        },
        changeType() {
            for (var i = 0; i < this.typeList.length; i++) {
                var obj = this.typeList[i]
                obj.values = ''
                obj.names = ''
            }
            this.getValues()
        },
        aliskt() {
            this.getValues()
        },
        getValues() {
            if (this.allType) {
                var resultData = {
                    label: this.formBoListI18n('all','所有人'),
                    value: 'everyone'
                }
            } else {
                var names = []
                var typeListObj = {}
                for (var i = 0; i < this.typeList.length; i++) {
                    var typeObj = this.typeList[i]
                    if (!typeObj.names) {
                        continue
                    }
                    typeListObj[typeObj.type] = {
                        names: typeObj.names,
                        values: typeObj.values,
                        include: typeObj.include,
                    }
                    names.push(typeObj.name + ':' + typeObj.names)
                }

                if (names.length > 0) {
                    var resultData = {
                        label: names.join(';'),
                        value: JSON.stringify(typeListObj),
                    }
                } else {
                    var resultData = {
                        label: this.formBoListI18n('noConfig','无配置'),
                        value: 'custom'
                    }
                }
            }
            this.settingObj.setting = resultData.value;
            this.settingObj.settingName = resultData.label;
        }
    }
}
</script>
<style scoped>
.authority-list-common{
    display: flex;
    height: calc(100% - 40px);
}
.authority-common{
    flex: 1;
    padding: 17px;
    border-right: 1px solid #eeeeee;
}
.FormBoListEditPermissionConf-list-head{
    border-left: 2px solid #1890ff;
    height: 12px;
    line-height: 12px;
    padding-left: 8px;
}
.FormBoListEditPermissionConf-list-name{
    margin: 10px 0px 20px 10px;
}
.FormBoPermissionEdit-authority-list{
    width: 100%;
    flex: 1;
    display: flex;
    border-top: 1px solid #eeeeee;
}
.FormBoPermissionEdit-name-list{
    flex: 1;
}
.FormBoPermissionEdit {
    display: flex;
    height: 100%;
    width: 100%;
    flex-direction: column;
    padding: 0px 20px;
    box-sizing: border-box;
    overflow: hidden;
}

.FormBoPermissionEdit-head {
    display: flex;
    align-content: center;
}

.FormBoPermissionEdit-head-model {
    margin-right: 10px;
    width: 700px;
    display: flex;
    align-items: center;
}

.FormBoPermissionEdit-common {
    flex: 1;
    border-radius: 4px;
    border: solid 1px #eeeeee;
    margin-top: 5px;
    display: flex;
    width: 100%;
    overflow: auto;
}

.FormBoPermissionEdit-common-le {
    width: 35%;
    height: 100%;
    display: flex;
    flex-direction: column;
    border-right: 1px solid #eeeeee;;
}

.FormBoPermissionEdit-le_hear {
    height: 40px;
    line-height: 40px;
    border-bottom: solid 1px #eeeeee;
    padding-left: 24px;
    background-color: #fafafa;
    font-weight: bold;
}

.FormBoPermissionEdit-le_common {
    flex: 1;
    overflow: auto;
    box-sizing: border-box;
    padding: 25px 40px 10px 40px;
}
.FormBoPermissionEdit-common-ri{
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
}
.FormBoPermissionEdit-jurisdiction{
    padding:10px 24px 0px 24px;
    box-sizing: border-box;
}
.jurisdiction-common{
    min-height: 100px;
    border-radius: 4px;
    border: solid 1px #eeeeee;
    width: 100%;
    margin-bottom: 20px;
}
.jurisdiction-common-head{
    height: 40px;
    background-color: #fafafa;
    line-height: 40px;
    padding-left: 20px;
    border-bottom: solid 1px #eeeeee;
}
.jurisdiction-common-list{
    padding: 20px 20px 0px 20px;
}
.jurisdiction-common-checkbox >>> .ant-checkbox-group-item{
    margin-bottom: 8px;
    width: 100%;
}
.FormBoPermissionEdit-common-list{
    flex: 1;
    overflow: auto;
    display: flex;
    flex-direction: column;
}
.FormBoPermissionEdit-common-list-name{
    font-weight: bold;
    height: 40px;
    line-height: 40px;
    display: flex;
    padding: 0px 20px;
    border-bottom: solid 1px #eeeeee;
}
</style>
